package com.grantheath.erebus.model.loaders 
{
	import mx.events.ModuleEvent;
	import mx.modules.ModuleManager;
	import mx.modules.IModuleInfo;

	import com.grantheath.erebus.view.interfaces.IErebusPage;
	import com.grantheath.erebus.model.interfaces.IErebusPageLoader;
	import com.grantheath.erebus.model.interfaces.IErebusPageNode;
	import com.grantheath.erebus.view.pages.ErebusFlexPage;
	import com.grantheath.erebus.model.helpers.ErebusLoadEvent;

	import flash.events.Event;
	import flash.events.EventDispatcher;

	/**
	 * @author grantheath
	 */
	public class ErebusFlexPageLoader extends EventDispatcher implements IErebusPageLoader 
	{
		private var _pageNode : IErebusPageNode;
		private var _moduleLoader : IModuleInfo;
		private var _loadedPage : ErebusFlexPage;
		private var _bytesLoaded : Number;
		private var _bytesTotal : Number;

		public function loadPage(pageNode : IErebusPageNode) : void
		{
			_pageNode = pageNode;
			_moduleLoader = ModuleManager.getModule(pageNode.pageSrc);
			_moduleLoader.addEventListener(ModuleEvent.SETUP, dispatchOpenEvent);
			_moduleLoader.addEventListener(ModuleEvent.READY, dispatchCompleteEvent);
			_moduleLoader.addEventListener(ModuleEvent.PROGRESS, dispatchProgressEvent);
			_moduleLoader.addEventListener(ModuleEvent.ERROR, dispatchErrorEvent);
			_moduleLoader.load();
		}
		
		public function unloadPage() : void
		{
			_moduleLoader.release();
			_moduleLoader.unload();
		}

		//EVENT HANDELERS
		public function dispatchOpenEvent(event : Event) : void
		{
			dispatchEvent(new ErebusLoadEvent(ErebusLoadEvent.LOAD_OPEN));
		}
		
		public function dispatchCompleteEvent(event : Event) : void
		{
			_loadedPage = _moduleLoader.factory.create() as ErebusFlexPage;
			dispatchEvent(new ErebusLoadEvent(ErebusLoadEvent.LOAD_COMPLETE));
		}
		
		public function dispatchProgressEvent(event : Event) : void
		{
			var loadEvent : ModuleEvent = event as ModuleEvent;
			
			_bytesLoaded = loadEvent.bytesLoaded;
			_bytesTotal = loadEvent.bytesTotal;
			dispatchEvent(new ErebusLoadEvent(ErebusLoadEvent.LOAD_PROGRESS));
		}

		public function dispatchErrorEvent(event : Event) : void
		{
			dispatchEvent(new ErebusLoadEvent(ErebusLoadEvent.LOAD_ERROR));
		}

		//GETTERS AND SETTERS
		public function get loadedBytesCount() : uint
		{
			return _bytesLoaded;
		}

		public function get totalBytesCount() : uint
		{
			return _bytesTotal;
		}

		public function get percentLoaded() : Number
		{
			if(_bytesTotal == 0){
				return 0;
			}
			return _bytesLoaded / _bytesTotal;
		}

		public function get loadedPage() : IErebusPage
		{
			return _loadedPage;
		}
		
		public function get pageNode() : IErebusPageNode
		{
			return _pageNode;
		}
		
		public function set pageNode(pageNode : IErebusPageNode) : void
		{
			_pageNode = pageNode;
		}
	}
}
